import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Typography, 
  Avatar, 
  Descriptions, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Upload, 
  message,
  Row,
  Col 
} from 'antd';
import { 
  UserOutlined, 
  EditOutlined, 
  UploadOutlined, 
  SaveOutlined,
  LockOutlined 
} from '@ant-design/icons';
import type { UserInfo } from '../../types/layout';

const { Title } = Typography;

const Profile: React.FC = () => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    id: '1',
    username: 'admin',
    nickname: '管理员',
    email: 'admin@example.com',
    avatar: ''
  });
  
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  // 从localStorage获取用户信息
  useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      try {
        const parsed = JSON.parse(storedUserInfo);
        setUserInfo(parsed);
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }
  }, []);

  // 打开编辑模态框
  const handleEdit = () => {
    form.setFieldsValue(userInfo);
    setEditModalVisible(true);
  };

  // 保存用户信息
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const updatedUserInfo = { ...userInfo, ...values };
      setUserInfo(updatedUserInfo);
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));
      message.success('个人信息更新成功');
      setEditModalVisible(false);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  // 修改密码
  const handlePasswordChange = async () => {
    try {
      const values = await passwordForm.validateFields();
      // 这里应该调用API修改密码
      console.log('Password change:', values);
      message.success('密码修改成功');
      setPasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (error) {
      console.error('Password validation failed:', error);
    }
  };

  // 头像上传
  const handleAvatarUpload = (info: any) => {
    if (info.file.status === 'done') {
      message.success('头像上传成功');
      // 这里应该更新头像URL
    } else if (info.file.status === 'error') {
      message.error('头像上传失败');
    }
  };

  return (
    <div>
      <Row gutter={24}>
        <Col span={24}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '24px' }}>
              <Avatar 
                size={80} 
                icon={<UserOutlined />} 
                src={userInfo.avatar}
                style={{ backgroundColor: '#1890ff' }}
              />
              <div style={{ marginLeft: '16px' }}>
                <Title level={3} style={{ margin: 0 }}>
                  {userInfo.nickname}
                </Title>
                <p style={{ color: '#666', margin: '4px 0 0 0' }}>
                  @{userInfo.username}
                </p>
              </div>
              <div style={{ marginLeft: 'auto' }}>
                <Space>
                  <Button 
                    type="primary" 
                    icon={<EditOutlined />}
                    onClick={handleEdit}
                  >
                    编辑资料
                  </Button>
                  <Button 
                    icon={<LockOutlined />}
                    onClick={() => setPasswordModalVisible(true)}
                  >
                    修改密码
                  </Button>
                </Space>
              </div>
            </div>

            <Descriptions title="基本信息" bordered column={2}>
              <Descriptions.Item label="用户名">
                {userInfo.username}
              </Descriptions.Item>
              <Descriptions.Item label="昵称">
                {userInfo.nickname}
              </Descriptions.Item>
              <Descriptions.Item label="邮箱">
                {userInfo.email}
              </Descriptions.Item>
              <Descriptions.Item label="用户ID">
                {userInfo.id}
              </Descriptions.Item>
              <Descriptions.Item label="注册时间">
                2024-01-01 10:00:00
              </Descriptions.Item>
              <Descriptions.Item label="最后登录">
                2024-01-15 10:30:00
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
      </Row>

      {/* 编辑个人信息模态框 */}
      <Modal
        title="编辑个人信息"
        open={editModalVisible}
        onOk={handleSave}
        onCancel={() => setEditModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="昵称"
            name="nickname"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/api/upload"
              onChange={handleAvatarUpload}
            >
              {userInfo.avatar ? (
                <img src={userInfo.avatar} alt="avatar" style={{ width: '100%' }} />
              ) : (
                <div>
                  <UploadOutlined />
                  <div style={{ marginTop: 8 }}>上传头像</div>
                </div>
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onOk={handlePasswordChange}
        onCancel={() => setPasswordModalVisible(false)}
        okText="确认修改"
        cancelText="取消"
      >
        <Form form={passwordForm} layout="vertical">
          <Form.Item
            label="当前密码"
            name="currentPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password placeholder="请输入当前密码" />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile;